using Cinemachine;
using CinemachineExtend;
using Services;
using UnityEngine;

public class CameraDoll : MonoBehaviour
{
    private PerformanceManager manager;
    private Player player;
    private CinemachineVirtualCamera vitualCamera;
    private EventSystem eventSystem;
    private CameraOffsetController cameraOffsetController;

    private void Awake()
    {
        manager = ServiceLocator.Get<PerformanceManager>();
        eventSystem = ServiceLocator.Get<EventSystem>();
        vitualCamera = Camera.main.GetComponentInChildren<CinemachineVirtualCamera>();
        player = ServiceLocator.Get<ActionController>().player;
        eventSystem.AddListener<EGameState, EGameState>(EEvent.GameStateChange, OnGameStateChange);
    }

    private void Start()
    {
        cameraOffsetController = Camera.main.GetComponentInChildren<CinemathineCore>().CameraOffsetController;
    }

    private void OnDestroy()
    {
        eventSystem.RemoveListener<EGameState, EGameState>(EEvent.GameStateChange, OnGameStateChange);
    }

    private void OnGameStateChange(EGameState from, EGameState to)
    {
        switch (to)
        {
            case EGameState.Performance:
                if (from == EGameState.Default && manager.CurrentPerformance.b_controlCamera)
                    StartControl();
                return;
            case EGameState.Default:
                if (from == EGameState.Performance && manager.CurrentPerformance.b_controlCamera)
                    EndControl();
                return;
        }
    }

    private void StartControl()
    {
        gameObject.SetActive(true);
        vitualCamera.Follow = transform;
    }

    private void EndControl()
    {
        gameObject.SetActive(false);
        vitualCamera.Follow = player.transform;
        cameraOffsetController.MyReset();
    }
}
